<template>
  <el-dialog v-model="visible" :title="isLogin ? '用户登录' : '用户注册'" width="400px" :close-on-click-modal="false"
    @close="resetForm">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" @submit.prevent="handleSubmit">
      <!-- 注册时显示邮箱 -->
      <el-form-item v-if="!isLogin" label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" type="email" />
      </el-form-item>

      <!-- 用户名 -->
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>

      <!-- 注册时显示确认密码 -->
      <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
      </el-form-item>

      <!-- 注册时显示昵称 -->
      <el-form-item v-if="!isLogin" label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="请输入昵称（可选）" />
      </el-form-item>

      <!-- 登录时显示记住我 -->
      <el-form-item v-if="isLogin">
        <el-checkbox v-model="form.rememberMe">记住我</el-checkbox>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ isLogin ? '登录' : '注册' }}
        </el-button>
      </div>

      <div class="auth-options">
        <el-divider>
          <span class="divider-text">其他登录方式</span>
        </el-divider>

        <div class="switch-mode">
          <el-button type="text" @click="toggleMode">
            {{ isLogin ? '没有账号？立即注册' : '已有账号？立即登录' }}
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useUserStore } from '../stores/user'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const userStore = useUserStore()
const formRef = ref()
const loading = ref(false)
const isLogin = ref(true)

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const form = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  rememberMe: false
})

const rules = computed(() =>
{
  const baseRules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 50, message: '用户名长度在 3 到 50 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
  }

  if (!isLogin.value)
  {
    baseRules.email = [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
    baseRules.confirmPassword = [
      { required: true, message: '请确认密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) =>
        {
          if (value !== form.password)
          {
            callback(new Error('两次输入密码不一致'))
          } else
          {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
  }

  return baseRules
})

const handleSubmit = async () =>
{
  if (!formRef.value) return

  try
  {
    await formRef.value.validate()
    loading.value = true

    let result
    if (isLogin.value)
    {
      result = await userStore.login({
        username: form.username,
        password: form.password,
        rememberMe: form.rememberMe
      })
    } else
    {
      result = await userStore.register({
        username: form.username,
        email: form.email,
        password: form.password,
        confirmPassword: form.confirmPassword,
        nickname: form.nickname || form.username
      })
    }

    if (result.success)
    {
      if (isLogin.value)
      {
        visible.value = false
        emit('success')
      } else
      {
        // 注册成功后切换到登录模式
        isLogin.value = true
        resetForm()
      }
    }
  } catch (error)
  {
    console.error('表单验证失败:', error)
  } finally
  {
    loading.value = false
  }
}

const checkLoginStatus = async () =>
{
  try
  {
    // 检查用户是否已登录
    await userStore.checkLoginStatus()
    if (userStore.isLoggedIn)
    {
      visible.value = false
      emit('success')
      ElMessage.success('登录成功')
    }
  } catch (error)
  {
    console.error('检查登录状态失败:', error)
  }
}

const toggleMode = () =>
{
  isLogin.value = !isLogin.value
  resetForm()
}

const resetForm = () =>
{
  if (formRef.value)
  {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    username: '',
    email: '',
    password: '',
    confirmPassword: '',
    nickname: '',
    rememberMe: false
  })
}

onMounted(() =>
{
  // 组件初始化
})
</script>

<style scoped>
/* 对话框整体样式 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 24px 24px 20px;
  margin: 0;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
  font-size: 20px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

:deep(.el-dialog__body) {
  padding: 32px 24px 24px;
  background: #fafbfc;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 4px 12px rgba(102, 177, 255, 0.3);
}

/* 按钮样式优化 */
.dialog-footer {
  text-align: center;
  margin-top: 24px;
}

.dialog-footer .el-button {
  border-radius: 12px;
  padding: 12px 32px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.dialog-footer .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.dialog-footer .el-button--primary:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}

.auth-options {
  border-top: 1px solid #e4e7ed;
  padding-top: 24px;
  margin-top: 24px;
}

.divider-text {
  color: #909399;
  font-size: 14px;
  font-weight: 500;
}

.social-login {
  margin: 20px 0;
}

.social-login .el-button {
  width: 100%;
  border-radius: 12px;
  padding: 14px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #1aae88 0%, #2dd4bf 100%);
  border: none;
  color: white;
  box-shadow: 0 4px 12px rgba(26, 174, 136, 0.3);
}

.social-login .el-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(26, 174, 136, 0.4);
}

.social-login .el-button:disabled {
  background: #f5f7fa;
  color: #c0c4cc;
  box-shadow: none;
  cursor: not-allowed;
}

.switch-mode {
  text-align: center;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

.switch-mode .el-button--text {
  color: #667eea;
  font-weight: 500;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.switch-mode .el-button--text:hover {
  color: #764ba2;
  background: rgba(102, 126, 234, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 5vh auto;
  }

  :deep(.el-dialog__body) {
    padding: 24px 20px 20px;
  }

  .dialog-footer .el-button {
    width: 100%;
    margin-bottom: 12px;
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  border-radius: 12px;
}

/* 表单验证错误样式 */
:deep(.el-form-item.is-error .el-input__wrapper) {
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.3);
}

:deep(.el-form-item__error) {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}
</style>
